<template>
  <div>
    <h1>用户管理</h1>
    <button @click="addUser">新增用户</button>
    <ul>
      <li v-for="user in users" :key="user.id">
        {{ user.name }}--{{ user.age }}
        <button @click="editUser(user.id)">修改</button>
        <button @click="deleteUser(user.id)">删除</button>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'

import { getUsersApi, deleteUserApi } from '@/api/users.js'

const users = ref([])
const router = useRouter()

const getUsers = async () => {
  // 使用axios发送请求，调接口获取数据
  users.value = await getUsersApi()
}

onMounted(getUsers)

const addUser = () => {
  // 切换路由
  router.push('/user/add')
}

const editUser = (id) => {
  // 切换路由
  router.push(`/user/edit/${id}`)
}

const deleteUser = async (id) => {
  await deleteUserApi(id)
  getUsers()
}
</script>

<style scoped></style>
